<template>
<div>
	<!-- 广告组列表 -->
    <!-- 加载 -->
    <div class="example">
        <a-spin size="large" tip="Loading..." :spinning="spinning" />
    </div>
<div v-if="spinning ==false">
  <a-card>
    <div :class="advanced ? 'search' : null">
      <a-form layout="horizontal" :form="form" @submit="handleSubmit">
        <div :class="advanced ? null: 'fold'">
          <a-row >
          <a-col :md="8" :sm="24" >
            <a-form-item
              label="广告组状态"
              :labelCol="{span: 5}"
              :wrapperCol="{span: 18, offset: 1}"
            >
              <a-select 
			  v-decorator="[
				'status',
				]"
			  placeholder="请选择广告组状态" :allowClear="true">
                <a-select-option value="CAMPAIGN_STATUS_ENABLE">启用</a-select-option>
                <a-select-option value="CAMPAIGN_STATUS_DISABLE">暂停</a-select-option>
				<a-select-option value="CAMPAIGN_STATUS_DELETE">删除</a-select-option>
				<a-select-option value="CAMPAIGN_STATUS_ALL">所有包含已删除</a-select-option>
				<a-select-option value="CAMPAIGN_STATUS_NOT_DELETE">所有不包含已删除（状态过滤默认值）</a-select-option>
				<a-select-option value="CAMPAIGN_STATUS_ADVERTISER_BUDGET_EXCEED">超出广告主日预算</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" >
            <a-form-item
              label="关键词搜索"
              :labelCol="{span: 5}"
              :wrapperCol="{span: 18, offset: 1}"
            >
              <a-input v-decorator="[
				'campaign_name',
				]"
		 placeholder="请输入名称或ID搜索" />
            </a-form-item>
          </a-col>
			<a-col :md="8" :sm="24" >
				<a-form-item
				label="统计时间范围"
				:labelCol="{span: 5}"
				:wrapperCol="{span: 18, offset: 1}"
				>
					<a-range-picker v-decorator="[
					'campaign_create_time',
					
					]" 
					:disabled-date="disabledDate"
					/>
				</a-form-item>
			</a-col>

        </a-row>
          <a-row v-if="advanced">
         
          <a-col :md="8" :sm="24" >
            <a-form-item
              label="推广目的"
              :labelCol="{span: 5}"
              :wrapperCol="{span: 18, offset: 1}"
            >
              <a-select v-decorator="[
				'landing_type',
				]"  placeholder="请选择" :allowClear="true">
                <a-select-option value="LINK">销售线索收集</a-select-option>
                <a-select-option value="APP">应用推广</a-select-option>
                <a-select-option value="DPA">商品目录推广</a-select-option>
                <a-select-option value="GOODS">商品推广</a-select-option>
                <a-select-option value="STORE">门店推广</a-select-option>
                <a-select-option value="AWEME">抖音号推广</a-select-option>
                <a-select-option value="SHOP">电商店铺推广</a-select-option>
                <a-select-option value="ARTICAL">头条文章推广</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

           <a-col :md="8" :sm="24" >
            <a-form-item
              label="投放账户"
              :labelCol="{span: 5}"
              :wrapperCol="{span: 18, offset: 1}"
            >
              <a-select v-decorator="[
				'account_id',
				]" placeholder="请选择投放账户" :allowClear="true">
                <a-select-option v-for="(item,index) in datalist" :key="index" :value="item.account_id">{{item.account_id}}({{item.name}})</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
         
        </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
          <a-button type="primary" @click="queryresult">查询</a-button>
          <a-button @click="btncancel" style="margin-left: 8px">重置</a-button>
          <a @click="toggleAdvanced" style="margin-left: 8px">
            {{advanced ? '收起' : '展开'}}
            <a-icon :type="advanced ? 'up' : 'down'" />
          </a>
        </span>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button @click="addNew" type="primary">新建</a-button>
        <!-- <a-button >批量操作</a-button> -->
        <a-dropdown>
          <a-menu @click="handleMenuClick" slot="overlay">
            <a-menu-item key="enables">启用</a-menu-item>
            <a-menu-item key="suspend">暂停</a-menu-item>
            <a-menu-item key="delete">删除</a-menu-item>
          </a-menu>
          <a-button>
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
        <a-button @click="synction"><a-icon type="sync" />同步</a-button>
      </div>

      <a-modal
        title="选择同步广告投放账号"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
		:width="700"
      >
		<p>说明:同步时间与数量相关,确认后将自动同步,请耐心等待</p>
		<a-input-search placeholder="请输入名称或ID搜索" style="width: 200px;margin-bottom:16px;" @search="onSearch" />

		<a-table :row-selection="rowacountlist" :columns="acountlabel" :scroll="{ x: 210, y: 500 }" :pagination="false" :data-source="datalist">
			<a slot="name" slot-scope="text">{{ text.name }}</a>
		</a-table>
      
      </a-modal>

		<div class="spindiv">
		 	<a-spin :spinning="spinnings" tip="正在执行，请稍等..." />
		</div>
		
		<div v-if="spinnings == false">
			 <a-table
        :columns="columns"
        :dataSource="dataSource.list"
        :selectedRows.sync="selectedRows"
        @clear="onClear"
		@change="onChange"
		:pagination="paginationOpt"
       	:row-selection="rowSelection"
		:loading='tableloading'
	   	:scroll="{ x: 1500 }"
      >
	  
		<div slot="switchDemo" slot-scope="text,record,index">
			<a-switch :checked="text.status == 'CAMPAIGN_STATUS_ENABLE' ? true : false" :loading="text.switchloading" @change="onChangedata(text.id,text.account_id,index,$event)" />
		</div>

		<div slot="mainDemo" slot-scope="text">
			<span>
				{{text.account_id}}
				<p>{{text.ocean_account.name}}</p>
			</span>
		</div>

	<!-- 预算 -->
		<div slot="budgetmode" slot-scope="text">
           <span v-if="text =='BUDGET_MODE_DAY'">日预算</span>
            <span v-else-if="text == 'BUDGET_MODE_TOTAL'">总预算</span>
            <span v-else>不限</span>
        </div>

<!-- 类型 -->
		<div slot="typeDemo" slot-scope="text">
           <span v-if="text =='LINK'">销售线索收集</span>
		   <span v-else-if="text == 'APP'">应用推广</span>
		   <span v-else-if="text == 'DPA'">商品目录推广</span>
		   <span v-else-if="text == 'GOODS'">商品推广（鲁班）</span>
		   <span v-else-if="text == 'STORE'">门店推广</span>
		   <span v-else-if="text == 'AWEME'">抖音号推广</span>
		   <span v-else-if="text == 'SHOP'">电商店铺推广</span>
		   <span v-else-if="text == 'ARTICAL'">头条文章推广</span>
		   <span v-else>不限</span>
        </div>

	<!-- 状态 -->
		<div slot="statusDemo" slot-scope="text">
           <span v-if="text =='CAMPAIGN_STATUS_ENABLE'">启用</span>
		   <span v-else-if="text == 'CAMPAIGN_STATUS_DISABLE'">暂停</span>
		   <span v-else-if="text == 'CAMPAIGN_STATUS_DELETE'">删除</span>
		   <span v-else-if="text == 'CAMPAIGN_STATUS_ALL'">所有包含已删除</span>
		   <span v-else-if="text == 'CAMPAIGN_STATUS_NOT_DELETE'">所有不包含已删除</span>
		   <span v-else-if="text == 'CAMPAIGN_STATUS_ADVERTISER_BUDGET_EXCEED'">超出广告主日预算</span>
		   <span v-else>不限</span>
        </div>

        <div slot="deliveryDome" slot-scope="text">
          <span v-if="text =='MANUAL'">
            手动
          </span>
          <span v-else-if="text =='PROCEDURAL'">
            自动投放管家
          </span>
        </div>

    <!-- 操作 -->
	   <div slot="action" slot-scope="text">
          <a style="margin-right: 8px" @click="editRecord(text)">
            <a-icon type="edit"/>编辑
          </a>
          <!-- <a @click="deleteRecord(record.key)">
            <a-icon type="delete" />删除
          </a> -->
        </div>
      </a-table>

	  <!-- <pagination
	  	:total="dataSource.page_info.total"
	  	:page_size="dataSource.page_info.page_size"
		@queryresult="queryresult"
	  ></pagination> -->

		</div>
    </div>
  </a-card>
</div>
</div>
</template>

<script>
import {ADVER,ACCOUNTURL,SYNCURL,ADVERUPDATE} from '@/services/api'
import moment from 'moment';
// import StandardTable from '@/components/table/StandardTable'
import {ajaxparems,ajaxnoparams} from '@/services/ajaxrequest'
// import pagination from "@/components/Pagination";
const columns = [
	{
		title: '',
		width: 60,
		fixed: 'left',
		scopedSlots: { customRender: 'switchDemo' }
	},
{
	title: '广告主',
	width:220,
	fixed: 'left',
	scopedSlots: { customRender: 'mainDemo' }
  },

  {
	title: '广告组名称',
	width:220,
	fixed: 'left',
    dataIndex: 'name'
  },
  {
	title: '广告组预算',
	width:130,
    dataIndex: 'budget'
  },
  {
	title: '广告组预算类型',
	width:130,
	dataIndex: 'budget_mode',
	scopedSlots: { customRender: 'budgetmode' }
  },
  {
	title: '广告目的',
	width:130,
	dataIndex: 'landing_type',
	scopedSlots: { customRender: 'typeDemo' }
  },
  {
	title: '广告组状态',
	width:130,
	dataIndex: 'status',
	scopedSlots: { customRender: 'statusDemo' }
  },
   {
	title: '创建时间',
	width:130,
	dataIndex: 'campaign_create_time',
  },
  {
	title: '修改时间',
	width:130,
	dataIndex: 'campaign_modify_time',
  },
   {
	title: '投放类型',
	width:130,
  dataIndex: 'delivery_mode',
  scopedSlots: { customRender: 'deliveryDome' }
  },
    {
	title: '消耗',
	width:130,
	sorter: (a, b) => a.cost - b.cost,
    dataIndex: 'cost'
  },
  {
	title: '点击数',
	width:130,
	sorter: (a, b) => a.click - b.click,
    dataIndex: 'click'
  },
    {
	title: '展示数',
	width:130,
	sorter: (a, b) => a.show - b.show,
    dataIndex: 'show'
  }, {
	title: '转化数',
	width:130,
	sorter: (a, b) => a.convert - b.convert,
    dataIndex: 'convert'
  },{
	title: '千次展示成本',
	width:130,
	sorter: (a, b) => a.show_cost - b.show_cost,
    dataIndex: 'show_cost'
  },{
	title: '点击成本',
	width:130,
	sorter: (a, b) => a.click_cost - b.click_cost,
    dataIndex: 'click_cost'
  },
  {
	title: '点击率',
	width:130,
	sorter: (a, b) => a.click_rate - b.click_rate,
    dataIndex: 'click_rate'
  },
  {
	title: '转化成本',
	width:130,
	sorter: (a, b) => a.convert_cost - b.convert_cost,
    dataIndex: 'convert_cost'
  },
   {
	title: '转化率',
	width:130,
	sorter: (a, b) => a.convert_rate - b.convert_rate,
    dataIndex: 'convert_rate'
  },
  {
	title: '操作',
	width:130,
	fixed:'right',
    dataIndex: 'id',
    scopedSlots: { customRender: 'action' }
  },
]
var acountlabel = [
	{
		title:'广告账号',
		scopedSlots: { customRender: 'name' }
	}
]
var dataSource = [];
var datalist =[];
export default {
	  name: 'QueryList',
	//   components:{pagination},
   	created(){
		this.form = this.$form.createForm(this);
		this.spinning = true;
		this.listNew();
		this.accountlist();
	},
	beforeCreate() {
		this.form = this.$form.createForm(this);
	},
	inject:['reload'],
	data () {
		return {
			spinning:true,
			advanced: false,
			columns: columns,
			dataSource:dataSource,
			selectedRowslist: [],
			visible:false,
			acountlabel,
			datalist,
			checkaccount:[],
			spinnings:false,
			tableloading:true,
			dateData:[],
			
			paginationOpt: {
				defaultCurrent: 1, // 默认当前页数
				defaultPageSize: 10, // 默认当前页显示数据的大小
				total: 0, // 总数，必须先有
				showSizeChanger: true,
				showQuickJumper: true,
				pageSizeOptions: ["5", "10", "15", "20"],
				showTotal: (total) => `共 ${total} 条`, // 显示总数
				onShowSizeChange: (current, pageSize) => {
					this.paginationOpt.defaultCurrent = current;
					this.paginationOpt.defaultPageSize = pageSize;
					this.listNew(); //显示列表的接口名称
				},
				// 改变每页数量时更新显示
				onChange: (current, size) => {
					console.log(current);
					this.paginationOpt.defaultCurrent = current;
					this.paginationOpt.defaultPageSize = size;
					this.listNew();
				},
			},
		}
	},
	authorize: {
		deleteRecord: 'delete'
	},

  	methods: {
		moment,
		getCurrentData(){
			return new Date().toLocaleDateString();
		},
		disabledDate(current) {
			//  return time.getTime() > Date.now();
			// return current && current >=moment().subtract(1, "days");
			return current && current >= moment().endOf('day');
		},
		synction(){
			//同步
			this.visible = true;
		},
		handleCancel(){
			// 取消同步
			this.visible = false;
		},
		onSearch(e){
			// 同步账号搜索
			var parems = {"filtering":[
				{"field":'name',"operator":'LIKE',"value":e},
			]};
			ajaxparems(ACCOUNTURL,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
					this.datalist =result.data;
					// this.reload();
				}else{
 					this.$message.error(result.message, 3)
				}
			})
		},
		handleOk(){
			// 确定同步
			if(this.checkaccount.length <=0){
				this.$message.error("请选择同步账号");
				return;
			}
			var accountlist = [];
			this.checkaccount.forEach((res)=>{
				accountlist.push(res.account_id);
			})
			var parems = {"account_ids":accountlist,"type":'CAMPAIGN'}
			ajaxparems(SYNCURL,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
					this.visible = false;
					this.$message.success(result.message,3);
					this.reload();
				}else{
					this.visible = false;
					this.$message.error(result.message, 3)
				}
			})
		},
		deleteRecord(key) {
			this.dataSource = this.dataSource.filter(item => item.key !== key)
			this.selectedRows = this.selectedRows.filter(item => item.key !== key)
		},
		btncancel(){
			//   重置
			this.form.resetFields();
			this.listNew();
		},

		//改变状态
		onChangedata(id,account_id,index,e){
			this.dataSource.list[index].switchloading = true;
			//更改广告组状态
			var parems = {}
			if(e ==true){
				parems = {"advertiser_id":account_id,"campaign_ids":[id],"opt_status":'enable'}
			}else{
				parems = {"advertiser_id":account_id,"campaign_ids":[id],"opt_status":'disable'}
			}
			ajaxnoparams(account_id, ADVERUPDATE,parems).then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
					if(e ==true){
						this.dataSource.list[index].status = 'CAMPAIGN_STATUS_ENABLE';
					}else{
						this.dataSource.list[index].status = 'CAMPAIGN_STATUS_DISABLE';
					}
					this.dataSource.list[index].switchloading = false;
					this.$message.success(result.message,3);
				}else{
					this.$message.error(result.message,3);
				}
			})
		},
		queryresult(){
			// 查询条件
			this.paginationOpt.defaultCurrent = 1;
			this.paginationOpt.defaultPageSize = 10;

			console.log(this.paginationOpt);

			this.listNew();
		},
		handleSubmit(res){
			console.log(res);
		},
		toggleAdvanced () {
		this.advanced = !this.advanced
		},
		remove () {
		this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
		this.selectedRows = []
		},
		onClear() {
		this.$message.info('您清空了勾选的所有行')
		},
		onStatusTitleClick() {
		this.$message.info('你点击了状态栏表头')
		},
		// onChange() {
		// // this.$message.info('表格状态改变了')
		// },
		onSelectChange() {
		this.$message.info('选中行改变了')

		},
		addNew () {
			this.$router.push('/promotion/advering/addadver/?tabs=1')
		},
		editRecord(e){
			this.$router.push({
				path: '/promotion/advering/editaddver/?tabs=1',
				query: {
					ids: e,
				}
			})
		},
		accountlist(){
			// 获取广告主账号
			ajaxparems(ACCOUNTURL,"").then((res) => {
				var result=res.data;
				if(result.code =="SUCCESS"){
					this.datalist =result.data;
				}else{
 					this.$message.error(result.message, 3)
				}
			})
		},
		listNew() {
			this.tableloading = true;
			const { defaultCurrent, defaultPageSize } = this.paginationOpt;
			this.form.validateFieldsAndScroll((err, values) => {
				var parems = {};
				var paremsinfo = [];
				var time = '';
				var times = '';
				if(values['status'] !=undefined){
					if(values['status'] =="CAMPAIGN_STATUS_ALL"){
						// paremsinfo.push({"field":"status","operator":"IN","value":['CAMPAIGN_STATUS_DELETE']})
					}else if(values['status'] =='CAMPAIGN_STATUS_NOT_DELETE'){
						paremsinfo.push({"field":"status","operator":"NOT_IN","value":['CAMPAIGN_STATUS_DELETE']})
					}else{
						paremsinfo.push({"field":"status","operator":"EQUALS","value":values['status']})
					}
				}
				if(values['campaign_name'] !=undefined && values['campaign_name'] !=''){
					var numReg = /^[0-9]*$/
					var numRe = new RegExp(numReg)
					if (!numRe.test(values['campaign_name'])) {
						paremsinfo.push({"field":"name","operator":"LIKE","value":values['campaign_name']})
					}else{
						paremsinfo.push({"field":"id","operator":"LIKE","value":values['campaign_name']})
					}
				}

				if(values['campaign_create_time'] !=undefined && values['campaign_create_time'] !=''){
					time = moment(values['campaign_create_time'][0]).format('YYYY-MM-DD')
					times = moment(values['campaign_create_time'][1]).format('YYYY-MM-DD')
				}

				if(values['landing_type'] !=undefined){
					paremsinfo.push({"field":"landing_type","operator":"EQUALS","value":values['landing_type']})
				}
				if(values['account_id'] !=undefined){
					paremsinfo.push({"field":"account_id","operator":"EQUALS","value":values['account_id']})
				}
				if(paremsinfo.length >0){
					parems = {
						page:defaultCurrent,
						page_size:defaultPageSize,
						start_date:time,
						end_date:times,
						"filtering":paremsinfo,
					};
				}else{
					parems ={
						page:defaultCurrent,
						page_size:defaultPageSize,
						start_date:time,
						end_date:times,
						"filtering":[
						{"field":"status","operator":"NOT_IN","value":["CAMPAIGN_STATUS_DELETE"]}//不包含已删除
						
					]}
				}
				if(time =='' || times ==''){
					this.$delete(parems,'start_date');
					this.$delete(parems,'end_date');
				}
				// 获取默认广告组
				ajaxparems(ADVER,parems).then((res) => {
					var result=res.data;
					if(result.code =="SUCCESS"){
						result.data.list.map(v=>{
							v.switchloading = false				
						});
						this.paginationOpt.total = result.data.page_info.total;
						this.dataSource = result.data;
						this.tableloading = false;
					}else{
						this.tableloading = false;
						this.$message.error(result.message, 3)
					}
				})
			});
			
			this.spinning = false;
		},

		async gatherlist(arrlist,status){
			//数组集合（批量操作）
			let arr = []
			var parems = {};
			arrlist.forEach((res) =>{
				if(arr.indexOf(res.account_id) === -1){
					arr.push(res.account_id)
				}
			})
			for (let i = 0; i < arr.length; i++) {
				let arr2 = []
				arrlist.forEach(ele => {
					if(arr[i] === ele.account_id){
						arr2.push(ele.id)
					}
				});
				parems = {"advertiser_id":arr[i],"campaign_ids":arr2,"opt_status":status}
				await ajaxnoparams(arr[i], ADVERUPDATE,parems).then((res) => {
					var result=res.data;
					if(result.code =="SUCCESS"){
						this.$message.success(arr[i]+result.message,3);
					}else{
						this.$message.error(arr[i]+result.message,3);
					}
				})
			}
			this.spinnings = false;
			this.reload();
		},
		handleMenuClick (e) {
			// 批量操作
			if(this.selectedRowslist.length <=0){
				this.$message.error("请选择广告组");
				return;
			}
			this.spinnings = true;
			if (e.key === 'enables') {
				this.gatherlist(this.selectedRowslist,'enable');//启用
			}else if(e.key ==='suspend'){
				this.gatherlist(this.selectedRowslist,'disable');//停用
			}else if(e.key ==='delete'){
				this.gatherlist(this.selectedRowslist,'delete');//删除
			}
		}
  },computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
			this.selectedRowslist = selectedRows;
        //   console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
      };
    },
    rowacountlist() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
		//   console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
			this.checkaccount = selectedRows;
        },
      };
    }
  }
}
</script>

<style lang="less" scoped>

	.spindiv{
		text-align: center;
		background: rgba(0, 0, 0, 0.05);
		border-radius: 4px;
		margin-bottom: 20px;
		margin: 20px 0;
	}

  .example {
    text-align: center;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    margin-bottom: 20px;
    /* padding: 30px 50px; */
    margin: 20px 0;
  }
  .search{
    margin-bottom: 54px;
  }
  .fold{
    width: calc(100% - 216px);
    display: inline-block
  }
  .operator{
    margin-bottom: 18px;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
